import Vuex from 'vuex'
import Vue from 'vue'
import createPersistedState from 'vuex-persistedstate'

Vue.use(Vuex)

const store = new Vuex.Store({
  plugins: [
    createPersistedState({
      storage: window.sessionStorage
    })
  ],
  state: {
    // 初始化数据
    adminData:{
      username: '',
      userpassword:''
    },
    roleData:{},
    moduleData:[],
    update:true,
    token:'',
    // 标签页数据
    tabData:{
      editableTabsValue: '1',
      editableTabs: [{
        title: 'home',
        name: '1',
      }],
      tabIndex: 1
    }
  },
  getters:{

  },
  mutations: {
    // 标签页方法
    addTab(state,param){
      let flag=false;
      state.tabData.editableTabs.some(item=>{
        if(item.title==param.title||param.title==undefined){
          flag=true
          return true
        }
      })
      if(flag){ return }
      let newTabName = ++state.tabData.tabIndex + ''
      let newTab={
        title:param.title,
        name:newTabName,
        content:param.content
      }
      state.tabData.editableTabs.push(newTab)
      state.tabData.editableTabsValue = newTabName
    },
    removeTab(state,param){
      if(state.tabData.editableTabs.length<=1){
        return false
      }
      let tabs = state.tabData.editableTabs
      let activeName = state.tabData.editableTabsValue
      if (activeName === param) {
        tabs.forEach((tab, index) => {
          if (tab.name === param) {
            let nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              activeName = nextTab.name
            }
          }
        });
      }      
      state.tabData.editableTabsValue = activeName
      state.tabData.editableTabs = tabs.filter(tab => tab.name !== param)
    },
    changeActiveName(state,param){
      state.tabData.editableTabsValue=param
    },
    // 初始化数据方法
    appInit(state,loginData){
      // 初始化用户信息
      state.adminData=loginData.adminData
      state.roleData=loginData.roleData
      state.moduleData=loginData.moduleData
    },
    // 存储token
    setToken(state,param){
      state.token=param
    },
    logout (state) {
      state.adminData = {};
      state.roleData = {};
      state.moduleData = [];
      state.tabData ={
        editableTabsValue: '1',
        editableTabs: [{
          title: 'home',
          name: '1',
        }],
        tabIndex: 1
      };
      state.token = '';
    }
  },
  actions:{}
})

export default store
